package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.course.ListCourseMessage;
import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.jude.utils.JUtils;
import com.umeng.share.ShareManager;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.module.user.UserProfileActivity;
import com.xudow.app.network.OkHttpClientManager;
import com.xudow.app.newui.AgencyTeacherActivity;
import com.xudow.app.newui.ClassTimesTableActivity;
import com.xudow.app.newui.InspectionTeamActivity;
import com.xudow.app.newui.PreLoginActivity;
import com.xudow.app.newui.TeachSupervisionActivity;
import com.xudow.app.newui.bean.CourseDetaills;
import com.xudow.app.newui.task.okCourseDetailTask;
import com.xudow.app.newui.zutils.LsUtils;
import com.xudow.app.ui.task.CourseDetailTask;
import com.xudow.app.ui.task.CourseFavoriteTask;
import com.xudow.app.util.Maps;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by zhuchenxi on 16/6/27.
 */

public class CourseDetailActivity extends BaseActivity {
    @BindView(R.id.header_bar)
    RelativeLayout headerBar;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.image_share)
    ImageView share;
    @BindView(R.id.image_share2)
    ImageView image_share2;
    private Long courseId; //课程ID
    private Long classid;//OA扫描二维码传递过来查询课程详情
    String shareUrl;
    private final int ADDTOCART = 2;
    private final int ADDTOORD = 1;
   LinearLayout bottom;
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail2);
        ButterKnife.bind(this);

//        showLodingDialog("正在加载");
        bottom=(LinearLayout)findViewById(R.id.bottom);
        courseId = getIntent().getLongExtra("courseId", 0L);
        classid = getIntent().getLongExtra("classid", 0L);
        image_share2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent  intent = new Intent(getApplicationContext(), CartActivity.class);
//                startActivity(intent);
                XApplication application = (XApplication)getApplicationContext();
                if (!application.isLogin()) {
                    Intent intent1 = new Intent(getApplicationContext(), PreLoginActivity.class);
                    intent1.putExtra("closeAfterLogin", true);
                    startActivity(intent1);
                    return;
                }else{
                    Intent intent2=new Intent(getApplicationContext(),CartActivity.class);
                    startActivity(intent2);
                }
            }
        });
        initData();
        shareUrl = Config.BASE_URL + "external/website/share.jsp?courseid=" + (courseId == 0 ? classid : courseId);
        webview.loadUrl(Config.BASE_URL + "external/website/index.jsp?courseid=" + (courseId == 0 ? classid : courseId));
        webview.setVerticalScrollBarEnabled(false);
        webview.setHorizontalScrollBarEnabled(false);
        webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webview.getSettings().setDomStorageEnabled(true);

        webview.getSettings().setUseWideViewPort(true);
        webview.getSettings().setLoadWithOverviewMode(true);
        ProgressBar pg1=(ProgressBar) findViewById(R.id.progressBar1);

        webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
//                if(newProgress>=100){
//                    hideLoadingDialog();
//                }
                if(newProgress==100){
                    pg1.setProgress(100);//设置进度值

                    pg1.setVisibility(View.GONE);//加载完网页进度条消失

                }
                else{
                    pg1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    pg1.setProgress(newProgress + 15);//设置进度值
                }
            }
        });
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                String intentName = url.split(":")[0];
                Intent intent;
                switch (intentName) {
                    case "appaction-teaminfo"://督查团队
                        intent = new Intent(CourseDetailActivity.this, InspectionTeamActivity.class);
                        startActivity(intent);
                        break;
                    case "appaction-courseseat"://课程座位表
                        getSiteInfClik();
                        break;
                    case "appaction-schooladress"://地图
                        onAddressClick();
                        break;
                    case "appaction-teamassessment"://课程点评
                        String str[] = url.split("//");
                        gotoAssessment(str[1]);
                        break;
                    case "appaction-teacher"://个人老师
                        gotopage(url, 0);
                        break;
                    case "appaction-agency"://机构
                        gotopage(url, 1);
                        break;
                    case "appaction-agencyteacher"://机构老师
                        String agteacherId = url.split("//")[1];
                        if ("0".equals(agteacherId) || null == agteacherId) {
                           getMyApp().makeToast("找不到该老师信息");
                        } else {
                            intent = new Intent(CourseDetailActivity.this, AgencyTeacherActivity.class);
                            intent.putExtra("agencyTeacherId", agteacherId);
                            startActivity(intent);
                        }
                        break;
                    case "appaction-classtimes"://课程上课时间表
                        intent = new Intent(CourseDetailActivity.this, ClassTimesTableActivity.class);
                        intent.putExtra("courseId", url.split("//")[1]);
                        startActivity(intent);
                        break;

                    default:
                        if (url.contains("courseid=")) {
                            view.loadUrl(url);
                            courseId = Long.valueOf(url.split("courseid=")[1]);
//                            Log.e("re_courseId=", "" + courseId);
                            getProfile();
                        }

                }

                return true;

            }
        });

        webview.getSettings().setJavaScriptEnabled(true);

        String ua = webview.getSettings().getUserAgentString();

        String data = "Fivescoreyearsago,agreatAmerican,inwhosesymbolicshadowwestandtodaysignedtheEmancipationProclamationThismomentousdecreecameasagreatbeaconlightofhopetomillionsofNegroslaveswhohadbeensearedintheflamesofwitheringinjustice.Itcameasajoyousdaybreaktoendthelongnightofbadcaptivity.Butonehundredyearslater,theNegrostillisnotfree.OnehundredyearslaterthelifeoftheNegroisstillsadlycrippledbythemanaclesofsegregationandthechainsofdiscrimination.";
        webview.getSettings().setUserAgentString(ua + data);


    }

    /**
     * 课程督查 1,2,3,4
     */
    private void gotoAssessment(String page) {

        Intent intent = new Intent(this, TeachSupervisionActivity.class);

        intent.putExtra("page", Integer.valueOf(page));
        intent.putExtra("courseId", courseId + "");
        startActivity(intent);
    }


    private void gotopage(String url, int type) {

        long id = Long.valueOf(url.split("//")[1]);
        Intent i = new Intent(CourseDetailActivity.this, UserProfileActivity.class);
        if (0 == type)
            i.putExtra(UserProfileActivity.USER_PROFILE_ID, id);
        else
            i.putExtra(UserProfileActivity.AGNCY_ID, id);
        startActivity(i);
    }


    public void onBackBtnClick(View view) {
        finish();
    }


    /**
     * 获取用户数据
     */
    private void initData() {
        getProfile();
        share.setOnClickListener(v -> {
            String imageUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, course.getThumbnail());
            ShareAction action = ShareManager.getInstance(this).shareContent(this, course.getName() + "(" + course.getSchoolName() + ")", shareUrl, "学兜课程分享", imageUrl, new UMShareListener() {


                @Override
                public void onResult(SHARE_MEDIA share_media) {
                    JUtils.Toast("分享成功");
                }

                @Override
                public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                    JUtils.Toast("分享失败");
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media) {
                    JUtils.Toast("分享取消");
                }
            });

            action.setShareboardclickCallback((snsPlatform, share_media) -> {
                String platform = share_media.name();
                int type = 0;
                if (platform.equals(SHARE_MEDIA.QZONE.name()) || platform.equals(SHARE_MEDIA.QQ.name())) {
                    type = 2;
                } else if (platform.equals(SHARE_MEDIA.WEIXIN.name()) || platform.equals(SHARE_MEDIA.WEIXIN_CIRCLE.name())) {
                    type = 1;
                } else if (platform.equals(SHARE_MEDIA.SINA.name())) {
                    type = 3;

                }
                DynamicModel.getInstance().shareCount(courseId, type)
                        .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.NONE))
                        .subscribe();
            });

        });
    }

    private void getProfile() {
//        HashMap<String, String> params = new HashMap<String, String>();
//        params.put("courseid", "" + courseId);

//        Log.i("CourseDetailTask", "courseId>" + courseId);
//        CourseDetailTask courseDetailTask = new CourseDetailTask(this, courseDetailHandlers);
//        addTask(courseDetailTask);
//        courseDetailTask.execute(params);


        okCourseDetailTask okCourseDetailTask=new okCourseDetailTask(CourseDetailActivity.this,courseDetailHandler,courseId);
        okCourseDetailTask.cd();

        //showLodingDialog("正在加载");

    }

    /**
     * 获取课程详情Handler
     */
    CourseDetaills.CourseEntity course;
    private Handler courseDetailHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            hideLoadingDialog();

            if (CourseDetailTask.SUCCESS == msg.what) {
                bottom.setVisibility(View.VISIBLE);
                course = (CourseDetaills.CourseEntity) msg.getData().getSerializable("course");

//                hideLoadingDialog();
            } else{
                bottom.setVisibility(View.GONE);
               getMyApp().makeToast(msg.getData().getString("errMessage"));
                hideLoadingDialog();
            }


        }
    };


    /**
     * 获取购物车列表信息点击
     */
    public void onGetCarClick(View view) {
        XApplication application = (XApplication) getApplication();
        if (!application.isLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("closeAfterLogin", true);
            startActivity(intent);
            return;
        } else {
            //TODO 进入购物车页面
            Intent intent = new Intent(this, CartActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 加入收藏夹fggf按钮点击
     *
     * @param view
     */
    public void favoriteCourse(View view) {
        if(courseId!=null){
        XApplication application = (XApplication) getApplication();
        if (!application.isLogin()) {
            Intent intent = new Intent(this, PreLoginActivity.class);
            startActivity(intent);
            return;
        }

        showLodingDialog(getString(R.string.processing));

        HashMap<String, String> params = Maps.newHashMap();
        params.put("courseid", "" + courseId);

        CourseFavoriteTask courseFavoriteTask = new CourseFavoriteTask(this, courseFavoriteHandler);
        addTask(courseFavoriteTask);
        courseFavoriteTask.execute(params);
        }
    }

    /**
     * 加入收藏夹Handler
     */
    public Handler courseFavoriteHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
             hideLoadingDialog();
            if (CourseFavoriteTask.SUCCESS == msg.what) {
                String message = getString(R.string.favorite_success);
               getMyApp().makeToast(message);
            } else {
                if (msg.getData().get("errMessage") != null) {
                    String message = (String) msg.getData().get("errMessage");
                    getMyApp().makeToast(message);
                } else {
                    String message = getString(R.string.favorite_fail);
                    getMyApp().makeToast(message);

                }
            }
        }
    };
    private final int MORD = 1;
    private final int MCART = 2;

    /**
     * 立即支付按钮点击事件
     *
     * @param view
     */
    public void payIt(View view) {
        //课程有个status的状态，如果是 COURSE_STATUS_INVALID = 0 则表示无效了
      if(course!=null) {
          if (0 == course.getStatus()) {
              String msg = getString(R.string.course_invalid);
              getMyApp().makeToast(msg);
              return;
          }

          XApplication application = (XApplication) getApplication();
          if (!application.isLogin()) {

              Intent intent = new Intent(this, PreLoginActivity.class);

              startActivity(intent);
              return;
          }
          Intent intent = new Intent(getApplicationContext(), ChoseChildActivity.class);
          intent.putExtra("courseId_to_order", courseId);

          intent.putExtra("FLAGE", ADDTOORD);

          startActivity(intent);
      }
    }

    /**
     * 添加到购物车点击
     *
     * @param view
     */
    public void onAddCartClick(View view) {

      if(course!=null){

        //判断课程状态
        if (0 == course.getStatus()) {

            String msg = getString(R.string.course_invalid);
            getMyApp().makeToast(msg);

            return;
        }

        XApplication application = (XApplication) getApplication();
        if (!application.isLogin()) {

            Intent intent = new Intent(this, PreLoginActivity.class);

            startActivity(intent);
            return;
        }
        Intent intent = new Intent(this, ChoseChildActivity.class);
        intent.putExtra("courseId", courseId);
        intent.putExtra("FLAGE", ADDTOCART);

        startActivity(intent);

          }
    }

    /**
     * 查看课程选座情况
     */
    public void getSiteInfClik() {
        Intent intent = new Intent(this, SitesActivity.class);
        intent.putExtra("courseId", courseId + "");
        startActivity(intent);
    }

    /**
     * 地址点击事件
     *
     * @param
     */
    public void onAddressClick() {
        String address = "";

        if (null == course.getSchoolAdress() && null != course.getSchoolAdress())
            address = course.getSchoolAdress();
        else if (null != course.getSchoolAdress())
            address = course.getSchoolAdress();
        String url = String.format(Config.MAP_URL, course.getLongtitude(), course.getLatitude(),
                address);


        Intent intent = new Intent(this, MapViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", course.getSchoolAdress());

        startActivity(intent);
    }

}
